/*
 * Copyright (c) 2022-2023 cetcclout Co., Ltd All rights reserved.
 * Sensor Adapter is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.cetccloud.cimp.adapter.server.mqtt;

import com.cetccloud.cimp.adapter.config.ApplicationProperties;
import com.cetccloud.cimp.adapter.datasource.sqldb.vo.ServerConfig;
import com.cetccloud.cimp.adapter.protocol.ProtocolExecutor;
import com.cetccloud.cimp.adapter.protocol.chain.DefaultDataChain;
import com.cetccloud.cimp.adapter.util.SpringAppContextUtil;

import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.Buffer;
import java.util.UUID;

/**
 * @author
 * @apiNote 设置发布订阅服务连接
 * @date 2022/12/26 13:36
 */
public class MqttServer implements ProtocolExecutor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private String pwd;

    private final DefaultDataChain dataChain;
    private MqttServerCallback mqttServerCallback;
    private MqttAsyncClient asyncClient;

    public MqttServer(DefaultDataChain dataChain) {
    	ApplicationProperties ap = SpringAppContextUtil.getBean(com.cetccloud.cimp.adapter.config.ApplicationProperties.class);
    	this.pwd = ap.getMqtt().getPwd();
        this.dataChain = dataChain;
        this.mqttServerCallback = new MqttServerCallback(dataChain);
    }

    /**
     * 初始化MQTT链接客户端
     */
    public void mqttServerClient(String broker, String topic) {
        String clientId = "sensor-server-" + UUID.randomUUID();
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            asyncClient = new MqttAsyncClient(broker, clientId, persistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setAutomaticReconnect(true);
            connOpts.setCleanSession(true);

            // 设置超时时间 单位为秒
            connOpts.setConnectionTimeout(5);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            connOpts.setKeepAliveInterval(30);

            connOpts.setUserName(MqttSign.getUsername());
            connOpts.setPassword(this.pwd.toCharArray());

            asyncClient.setCallback(mqttServerCallback);
            IMqttToken connToken = asyncClient.connect(connOpts);
            connToken.waitForCompletion(1000L * 20);

            //初始化完成后订阅对应的主题信息
            asyncClient.subscribe(topic,2);
        } catch (MqttException e) {
            logger.warn("MqttException : {}", e.getMessage());
        }
    }

    /**
     * 获取信息处理操作集
     */
    @Override
    public DefaultDataChain getDefaultDataChain() {
        return this.dataChain;
    }

    /**
     * 绑定端口并启动服务
     */
    @Override
    public void start(ServerConfig serverConfig) {
        // tcp://172.29.0.69:1883

        String broker = serverConfig.getIp().startsWith("tcp://") ?
                serverConfig.getIp() + ":" + serverConfig.getPort(): "tcp://" + serverConfig.getIp() + ":" + serverConfig.getPort();
        String topic = serverConfig.getTopic();
        this.mqttServerClient(broker,topic);
    }

    /**
     * 结束服务实例
     */
    @Override
    public void quit() {
        try {
            this.asyncClient.close();
        } catch (MqttException e) {
            e.printStackTrace();
        }

    }

    /**
     * 数据发往设备
     */
	public void toDtu(Buffer buffer, Object context) {
		
	}

}
